package com.netty;

import cn.hutool.json.JSONUtil;
import io.netty.channel.*;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import lombok.extern.slf4j.Slf4j;

@ChannelHandler.Sharable
@Slf4j
public class MyClientHandler extends SimpleChannelInboundHandler<Object> {

	private final WebSocketClientHandshaker handshaker;

	private ChannelPromise handshakeFuture;

    public MyClientHandler(WebSocketClientHandshaker handshaker) {
        this.handshaker = handshaker;
    }

    @Override
	protected void channelRead0(ChannelHandlerContext ctx, Object obj) throws Exception {
		Channel incoming = ctx.channel();

		log.info("收到服务端的回复->{}", obj.toString());
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) {
		log.info("【Active】 [{}] is connected to the server", ctx.channel().remoteAddress());
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) {
		log.info("client disconnet with server");
		ctx.close();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		log.info("client disconnect error  with server->{}", cause.getMessage());
		ctx.close();
	}



	public ChannelFuture handshakeFuture() {
		return handshakeFuture;
	}


	@Override
	public void handlerAdded(ChannelHandlerContext ctx) {
		handshakeFuture = ctx.newPromise();
	}



}
